package com.dshore.messagecenter.controller.topicqueue;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.dshore.messagecenter.log.LogAnnotation;
import com.dshore.messagecenter.model.basedata.MdApp;
import com.dshore.messagecenter.model.system.ResponseResult;
import com.dshore.messagecenter.model.topicqueue.MdTopic;
import com.dshore.messagecenter.service.topicQueue.TopicQueueService;
import com.dshore.messagecenter.util.Page;
import com.dshore.messagecenter.util.RabbitUtil;




@Controller
@RequestMapping("/topicQueue/")
public class TopicQueueController {
	
	/**
	 * 使用 @Value 直接读取配置文件属性
	 * 该注解属于SpingMVC，不能配合static，静态一开始还没加载好框架，无法使用。
	 */
	//host
	@Value("${spring.rabbitmq.host}")
	private String host;
	
	//端口port
	@Value("${spring.rabbitmq.port}")
	private String port;
	
	@Autowired
	private TopicQueueService topicQueueService;
	private static final Logger logger = LoggerFactory.getLogger(TopicQueueController.class);
	
	@Autowired
	private RabbitUtil rabbitUtil;

	/**
	 * 手动同步主题队列配置
	 */
	@RequestMapping(value= "synchConfig",method = RequestMethod.POST)
	@ResponseBody
	public boolean synchConfig(String topicQueueNo) {
		return rabbitUtil.configSync(topicQueueNo);// true表示成功
	}

	/**
	 * 保存消息队列新增
	 */
	@LogAnnotation(targetType="主题队列消息队列",methodType="新增",argsName="topicQueueName")
	@RequestMapping(value= "saveApps",method = RequestMethod.POST)
	@ResponseBody
	public ResponseResult<Void> saveApps(String key, String topicQueueName, String status, HttpSession session) {
		Map<String, Object> map = (Map<String, Object>)session.getAttribute(key);
		
		// 校验名称不重复
		String id=null;
		if(map==null) {
			id="";
		}else {
			id=(String)map.get("tId");
			if(id==null) {
				id="";
			}
		}
		if(Pattern.compile("^[a-zA-Z0-9\\u4e00-\\u9fa5]{1,32}+$").matcher(topicQueueName).find()) {
			boolean flag = topicQueueService.checkAppName(topicQueueName,id);
			if(!flag) {
				return new ResponseResult<Void>(400,"新增有误");
			}
		}
		
		//清除2边空格
		String arr = "^[a-zA-Z0-9\u4e00-\u9fa5]{1,32}+$";
		
		// 校验不为空、不为特殊字符
		if(StringUtils.isNotBlank(topicQueueName)&&Pattern.compile(arr).matcher(topicQueueName.trim()).find()) {
			return topicQueueService.saveApps(map,topicQueueName,session,key,status);
		}else {
			return new ResponseResult<Void>(400,"新增失败");
		}
	}
	/**
	 * 保存消息队列修改
	 */
	@LogAnnotation(targetType="主题队列消息队列",methodType="修改",argsName="topicQueueName")
	@RequestMapping(value= "editApps",method = RequestMethod.POST)
	@ResponseBody
	public ResponseResult<Void> editApps(String key, String topicQueueName, String status, HttpSession session){
		Map<String, Object> map = (Map<String, Object>)session.getAttribute(key);
		/*	String arr = "^[a-zA-Z0-9\u4e00-\u9fa5]{1,32}+$";
		if(StringUtils.isNotBlank(topicQueueName)&&Pattern.compile(arr).matcher(topicQueueName.trim()).find()) {
			return topicQueueService.saveApps(map,topicQueueName,session,key,status);
		}else {
			return new ResponseResult<Void>(400,"修改失败");
		}*/
		// 校验名称不重复
				String id=null;
				if(map==null) {
					id="";
				}else {
					id=(String)map.get("tId");
					if(id==null) {
						id="";
					}
				}
				if(Pattern.compile("^[a-zA-Z0-9\\u4e00-\\u9fa5]{1,32}+$").matcher(topicQueueName).find()) {
					boolean flag = topicQueueService.checkAppName(topicQueueName,id);
					if(!flag) {
						return new ResponseResult<Void>(400,"修改有误");
					}
				}
				
				//清除2边空格
				String arr = "^[a-zA-Z0-9\u4e00-\u9fa5]{1,32}+$";
				
				// 校验不为空、不为特殊字符
				if(StringUtils.isNotBlank(topicQueueName)&&Pattern.compile(arr).matcher(topicQueueName.trim()).find()) {
					return topicQueueService.saveApps(map,topicQueueName,session,key,status);
				}else {
					return new ResponseResult<Void>(400,"修改失败");
				}
		
	}
	/**
	 * 主题队列页面
	 * @return
	 */
	@RequestMapping("page")
	public ModelAndView page() {
		ModelAndView mv = new ModelAndView("topicqueue/topicQueue");
		List<Map<String,Object>> accessType = topicQueueService.getAccessType();
//		System.out.println("accessType: " + accessType);
		
		mv.addObject("host", host); // host
		mv.addObject("port", port); // port
		mv.addObject("accessType", accessType);
		return mv;
	}

	/**
	 * 根据id获取队列配置信息
	 * @param id
	 * @return
	 */
	@RequestMapping(value="queryQueueConfig", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> queryQueueConfig(String id) {
		//队列信息
		MdTopic  topicQueue = topicQueueService.queryById(id);
		String topicQueueNo = topicQueue.getTopicQueueNo();
		//logger.info("主题队列编号: " + topicQueueNo);
		Map<String, Object> queue = new HashMap<String, Object>();
		if(StringUtils.isNotBlank(topicQueueNo)) {
			//源应用
			MdApp oriApp = topicQueueService.queryAppByAccess(topicQueueNo);
			//目标应用
			List<MdApp> targetApps = topicQueueService.queryAppsBySend(topicQueueNo);
			queue.put("topicQueue", topicQueue);
			queue.put("oriApp", oriApp);
			queue.put("targetApps", targetApps);
		}
		return queue;
	}


	/*@RequestMapping(value = "getTree", method = RequestMethod.POST)
    @ResponseBody
	public Map<String,String> getTree() {

	}*/


	/**
	 * 查询数据
	 * @param queue
	 * @return
	 */
	@RequestMapping(value = "getQueues", method = RequestMethod.POST)
	@ResponseBody
	public Page<Map<String, Object>> getMsgs(@RequestBody MdTopic queue) {
//		System.out.println("==============队列页面控制层==================");
		//		System.out.println("传入的源应用AppId: " + queue.getCheckAppId());

		//		System.out.println("第 " + queue.getOffset() + " 页, 每页行数: " + queue.getLimit());
		String arr1 = "^[a-zA-Z0-9\u4e00-\u9fa5]{1,32}+$";
		String arr2="^[A-Za-z0-9]{1,11}+$";
		if((StringUtils.isEmpty(queue.getTopicQueueNo())||Pattern.compile(arr2).matcher(queue.getTopicQueueNo()).find())&&(
				StringUtils.isEmpty(queue.getTopicQueueName())||Pattern.compile(arr1).matcher(queue.getTopicQueueName()).find())){
			try {
				return 	topicQueueService.queryListAll(queue,queue.getCheckAppId());
			} catch (Exception e) {
				e.printStackTrace();
				return null;
			}
		}else {
			return null;
		}	
	}
	/**
	 * 逻辑删除消息队列
	 * 
	 * @param id
	 */
	@LogAnnotation(targetType="删除",methodType="主题队列",argsName="idArr",tableName="T_MD_TOPIC",fieldName="TOPIC_QUEUE_NAME")
	@RequestMapping(value="deleteByIds")
	@ResponseBody
	public ResponseResult<Void> deleteByIds(String idArr, String statusArr) {
		//		System.out.println("删除控制层idArr: " + idArr + ", statusArr: " + statusArr);
		String[] statuses = statusArr.split(",");
		for(String status : statuses) {
			//			System.out.println("发布状态: " + status);
			//1302 已发布的需撤回后再发布
			if(status.equals("1302")) {
				return new ResponseResult<Void>(401,"您选择的队列有已发布的状态，请撤回后再试！");
			}
		}
		String[] ids = idArr.split(",");
		return topicQueueService.deleteByIds(ids);
	}

	/**
	 * 发布/ 撤回
	 */
	@RequestMapping(value="/releaseOrRecall")
	@ResponseBody
	public int releaseOrRecall(String id, int status, String topicQueueNo,
			String vhostName, String accessType) {
		//发布、撤回相互转换
		if(status == 1302) {
			return rabbitUtil.revocationTopicQueue(topicQueueNo);
//			//发布改撤回
//			status =1301;
//			//撤回流程
//			if(accessType.equals("1401")) {// 1401 服务接入撤回流程
//				System.out.println("服务撤回流程");
//				int result=topicQueueService.ServiceWidthdraw(topicQueueNo, id, status);
//				return result;	
//			}
//			else if(accessType.equals("1402")) {// 1402 消息队列撤回流程
//				//				System.out.println("消息队列撤回流程");
//				int result = topicQueueService.queueWidthdraw(topicQueueNo, vhostName, id, status);
//				System.out.println("撤回更新结果: " + result);
//				return result;
//			}
		} else if(status == 1301) {
			return rabbitUtil.publishTopicQueue(topicQueueNo);
//			//撤回改发布
//			status = 1302;
//			//发布流程
//			if(accessType.equals("1401")) {// 1401 服务接入发布流程
//				int result = topicQueueService.ServiceRelease(topicQueueNo,id,status);
//				return result;
//			}
//			else if(accessType.equals("1402")) {// 1402 消息队列发布流程
//				System.out.println("消息队列发布流程");
//				int result = topicQueueService.queueRelease(topicQueueNo, vhostName, id, status);
//				return result;
//			}
		} else {
			return 0;
		}
	}
	
	/*@RequestMapping(value="/getSourceAppName")
	@ResponseBody
	public List<List<String>> getSourceAppName(){
		List<List<String>> list=topicQueueService.getSourceAppName();
		return list;
	}
	
	@RequestMapping(value="/getTargetAppName")
	@ResponseBody
	public List<List<String>> getTargetAppName(){
		List<List<String>> list=topicQueueService.getTargetAppName();
		return list;
	}*/
}
